package com.woniuxy.shiro;


import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//JWT过滤器，拦截token信息
public class JWTFilter  extends BasicHttpAuthenticationFilter {

    /**
     * @Todo: 这里一般都是用于统一后台跨域解决！后端跨域的代码不能有多个，只能用一套方案！
     *      前端处理了后端就可以不写！
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }


    /**
     * @Todo: token认证入口，进行业务逻辑处理！和后续过滤器方法的调用
     * @param request
     * @param response
     * @param mappedValue
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //检查认证请求 获取请求头中的token
        if(isLoginAttempt(request,response)){
            try {
                //执行登录  subj.login
                executeLogin(request,response);
            } catch (Exception e) {
                //如果请求头中没有token  跳转到401请求！让401controller返回前端一个请求
                response401(request,response);
                e.printStackTrace();
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }


    /**
     * @Todo: 登录请求判断，尝试获取请求头中的token信息！
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
       HttpServletRequest request1= (HttpServletRequest) request;
        //从请求头中获取认证token信息
        String token = request1.getHeader("Authorization");
        return token!=null;
    }


    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest request1= (HttpServletRequest) request;
        //从请求头中获取认证token信息
        String token = request1.getHeader("Authorization");
        getSubject(request,response).login(new MyJsonWebToken(token));
        return true;
    }

    //如果请求头没有token则跳转401请求controller
    private void response401(ServletRequest request, ServletResponse response) {
        HttpServletResponse response1 = (HttpServletResponse) response;
        try {
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
